package org.test.rocketmq.producer04;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量消息发送。将消息汇聚成一批发送，增加吞吐量
 * <p>
 * <b>批量消息的大小不能超过 1MiB（否则需要自行分割），其次同一批 batch 中 topic 必须相同。</b>
 * </p>
 */
public class SimpleBatchProducerExample {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupName");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        String topic = "BatchTest";
        List<Message> messages = new ArrayList<>();
        messages.add(new Message(topic, "Tag", "OrderID011", "Hello world 0".getBytes()));
        messages.add(new Message(topic, "Tag", "OrderID012", "Hello world 1".getBytes()));
        messages.add(new Message(topic, "Tag", "OrderID013", "Hello world 2".getBytes()));

        SendResult sendResult = producer.send(messages);
        System.out.printf("%s%n", sendResult);
        // Shutdown producer after use.
        producer.shutdown();
    }
}
